﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
using BfLib.Web;
using BfLib.IO;

namespace BfLib.Web.RSSLite
{
    public class RSSLiteParser
    {
        private string _xmlText = string.Empty;
        private List<RSSLiteChannel> _channels;

        public RSSLiteParser(string Resource, TextResourceType ResType)
        {
            _channels = new List<RSSLiteChannel>();

            if (ResType == TextResourceType.XMLText)
            {
                this._xmlText = Resource;
            }
            else if (ResType == TextResourceType.Url)
            {
                this._xmlText = HTTPClient.DownloadText(Resource);
                //Resource is a http url, go get it and instantiate the Parser
            }
            else if (ResType == TextResourceType.Filename)
            {
                this._xmlText = FileLib.GetTextFromFile(Resource);
            }
            else return;

            ParseXml();

        }


        private void ParseXml()
        {
            RSSLiteChannel chan;
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(_xmlText);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);

            XmlNodeList nodes;
            string s = string.Empty;
            
            nodes = xml.SelectNodes("//rss/channel", nsmgr);  // returns null
            if (nodes == null)
                throw new Exception("No rss/channel elements found. This is required.");

            foreach(XmlNode chanNode in nodes)
            {
                chan = new RSSLiteChannel(chanNode);
                _channels.Add(chan);
            }
        }

        public List<RSSLiteChannel> Channels
        {
            get
            {
                return _channels;
            }
        }
    }
}
